/**
 * 权限控制工具
 */
import { getCookie } from "@/assets/js/cookie";
import { number } from "echarts";

// 路由权限配置
export const routePermissions = {
  // 管理员可以访问所有路由
  admin: [
    "Portal",
    "EquipmentBooking",
    "EquipmentBookingManage",
    "Equipment",
    "EquipmentDetails",
    "EquipmentDetailsLook",
    "EquipmentAlarm",
    "SystemNotify",
    "UserManage",
    "RoleManage",
    "OgaManage",
    "EquipmentTypes",
    "UpdatePassword",
  ],
  // 普通用户只能访问首页和设备预约
  user: [
    "Portal",
    "EquipmentBooking",
    "EquipmentAlarm",
    "SystemNotify",
    "EquipmentBookingManage",
    "EquipmentDetailsLook",
    "UpdatePassword",
  ],
  expert: [
    "Portal",
    "EquipmentBooking",
    "EquipmentBookingManage",
    "EquipmentAlarm",
    "SystemNotify",
    "EquipmentDetailsLook",
    "UpdatePassword",
  ],
};

/**
 * 获取用户角色
 * @returns 用户角色，默认为 'user'
 */
export const getUserRole = (): number[] => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const roleIds =
      userInfo.roles?.map((item: any) => {
        return item.id;
      }) || [];
    return roleIds;
  } catch (error) {
    console.error("获取用户角色失败:", error);
    return [3];
  }
};

/**
 * 检查用户是否有访问指定路由的权限
 * @param routeName 路由名称
 * @returns 是否有权限
 */
export const hasPermission = (routeName: string): boolean => {
  const userRoleIds = getUserRole();
  const userRole =
    userRoleIds.includes(1) || userRoleIds.includes(2)
      ? "admin"
      : userRoleIds.includes(4)
      ? "expert"
      : "user";
  const allowedRoutes =
    routePermissions[userRole as keyof typeof routePermissions] || [];
  return allowedRoutes.includes(routeName);
};

/**
 * 获取用户可访问的路由列表
 * @returns 可访问的路由名称数组
 */
export const getAccessibleRoutes = (): string[] => {
  const userRoleIds = getUserRole();
  const userRole =
    userRoleIds.includes(1) || userRoleIds.includes(2)
      ? "admin"
      : userRoleIds.includes(4)
      ? "expert"
      : "user";
  return routePermissions[userRole as keyof typeof routePermissions] || [];
};

/**
 * 检查用户是否已登录
 * @returns 是否已登录
 */
export const isLoggedIn = (): boolean => {
  const token = localStorage.getItem("token") || getCookie("token");
  return !!token;
};
